package org.gesplan.ui;

import ca.odell.glazedlists.swing.AutoCompleteSupport;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.Beans;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.gesplan.controller.GenericController;
import org.gesplan.controller.MaterialBuildingJpaController;
import org.gesplan.entity.Building;
import org.gesplan.entity.Material;
import org.gesplan.entity.MaterialBuilding;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.listeners.LoggingBindingListener;
import org.gesplan.listeners.SelectionListener;
import org.gesplan.util.ExcelManager;
import org.gesplan.util.RefreshWorker;
import org.gesplan.util.Utils;
import org.jdesktop.observablecollections.ObservableCollections;
import org.jdesktop.swingbinding.JTableBinding;

/**
 *
 * @author David
 */
@SuppressWarnings("rawtypes")
public class MaterialBuildingPanel extends AbstractPanel {

	private JTableBinding jTableBinding;
    private Building savedBuilding = null;
    private Date savedDateRel = null;
    private Date dateStart = null;
    private Date dateEnd = null;    
    private Building building = null;
    private Material material = null;
    private MaterialBuilding mb = null;    
	private static AutoCompleteSupport supportMaterial;
    
    
    public MaterialBuildingPanel() {
        super();
        try {
            initComponents();
        } catch (Exception e) {
            logger.log(Level.SEVERE, bundle.getString("ERROR_DB_CONNECTION"), e);
        }
        if (!Beans.isDesignTime()) {
            initConfig();
        }
    }

    
    public void refreshMaterials(){
        supportMaterial = GenericController.fillComboBox(bundle.getString("qryMaterial"), materialComboBox, supportMaterial);           
    }
    

    private void initConfig() {

        super.abstractTable = masterTable;
        super.abstractQuery = tableQuery;
        super.abstractList = tableList;

        // Add Listeners
        LoggingBindingListener lbl = new LoggingBindingListener(saveButton);
        bindingGroup.addBindingListener(lbl);
        masterTable.getSelectionModel().addListSelectionListener(new SelectionListener(masterTable, this));

        // Autocomplete Support for combos
        GenericController.fillComboBox(bundle.getString("qryBuilding"), buildingComboBox);
        //GenericController.fillComboBox(bundle.getString("qryMaterial"), materialComboBox);
        supportMaterial = GenericController.fillComboBox(bundle.getString("qryMaterial"), materialComboBox, supportMaterial);        
        GenericController.fillComboBox(bundle.getString("qryBuilding"), filterBuildingComboBox);
        GenericController.fillComboBox(bundle.getString("qryMaterial"), filterMaterialComboBox);

        initSorter();
        setHeaders();

        masterTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    editRecord();
                }
            }
        });
        
    }

    
    private void setHeaders(){
        Utils.setTableHeader(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(40);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        masterTable.getColumnModel().getColumn(3).setPreferredWidth(80);
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(50);
        masterTable.getColumnModel().getColumn(5).setPreferredWidth(50);
        masterTable.getColumnModel().getColumn(6).setPreferredWidth(50);    
    }
    
    
    private void editRecord() {
        if (masterTable.getSelectedRow() != -1) {
            mb = tableList.get(masterTable.convertRowIndexToModel(masterTable.getSelectedRow()));
        } else {
            mb = null;
        }
    }
    

    private void changeFilter() {

        if (Utils.isLoaded()) {
            Material material = null;
            String filterMaterial = null;
            String filterBuilding = null;
            // Get Filters
            dateStart = dateStartDateChooser.getDate();
            dateEnd = dateEndDateChooser.getDate();
            if (filterMaterialComboBox.getSelectedItem() instanceof Material) {
                material = (Material) filterMaterialComboBox.getSelectedItem();
            } else {
                filterMaterial = (String) filterMaterialComboBox.getSelectedItem();
            }
            if (filterBuildingComboBox.getSelectedItem() instanceof Building) {
                building = (Building) filterBuildingComboBox.getSelectedItem();
            } else {
                filterBuilding = (String) filterBuildingComboBox.getSelectedItem();
            }

            // Build JQL Query
            String jql = "SELECT mb FROM MaterialBuilding mb ";
            String where = null;
            if (filterMaterial != null) {
                where = "WHERE ";
                where += "(mb.id like '%" + filterMaterial + "%') OR (mb.description like '%" + filterMaterial + "%')";
            }
            if (material != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "mb.id = '" + material.getId() + "'";
            }
            if (filterBuilding != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "mb.buildingId.description like '%" + filterBuilding + "%'";
            }
            if (building != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "mb.buildingId.id = '" + building.getId() + "'";
            }
            if (dateStart != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "mb.dateRel >= '" + Utils.dateToString(dateStart) + "'";
            }
            if (dateEnd != null) {
                where = (where == null) ? "WHERE " : where + " AND ";
                where += "mb.dateRel <= '" + Utils.dateToString(dateEnd) + "'";
            }

            if (where != null) {
                jql += where;
            }
            jql += " ORDER BY mb.dateRel";
            updateTableBinding(jql);
        }

    }


    @SuppressWarnings("unchecked")
	private void updateTableBinding(String jql) {
        tableQuery = entityManager.createQuery(jql);
        tableList = ObservableCollections.observableList(tableQuery.getResultList());
        jTableBinding.unbind();
        jTableBinding.setSourceObject(tableList);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);
        setHeaders();
    }


    private void resetFilters() {
        dateStartDateChooser.setDate(null);
        dateEndDateChooser.setDate(null);
        filterMaterialComboBox.setSelectedIndex(-1);
        filterBuildingComboBox.setSelectedIndex(-1);
    }


    public boolean updateTotal() {
        
        if (Utils.isLoaded()) {
            double price;
            double amount;
            String aux = priceFieldOk.getText().replace(",", ".");
            String aux2 = amountFieldOk.getText().replace(",", ".");
            if (!aux.equals("") && !aux2.equals("")) {
                try {
                    price = (double) Double.parseDouble(aux);
                } catch (NumberFormatException e) {
                    logger.warning(bundle.getString("VALIDATE_NUMBER3") + ": " + e.getMessage());                    
                    priceFieldOk.requestFocusInWindow();
                    priceFieldOk.selectAll();
                    return false;
                }
                try {
                    amount = (double) Double.parseDouble(aux2);
                } catch (NumberFormatException e) {
                    logger.warning(bundle.getString("VALIDATE_NUMBER3") + ": " + e.getMessage());                    
                    amountFieldOk.requestFocusInWindow();
                    amountFieldOk.selectAll();
                    return false;
                }
                double total = price * amount;
                DecimalFormat twoDForm = new DecimalFormat("#.##");
                Double doubleAux = (Double) Double.parseDouble(twoDForm.format(total).replace(",", "."));                
                totalField.setText(doubleAux.toString());       
                doubleAux = (Double) Double.parseDouble(twoDForm.format(price).replace(",", "."));                
                priceFieldOk.setText(doubleAux.toString());         
                doubleAux = (Double) Double.parseDouble(twoDForm.format(amount).replace(",", "."));                
                amountFieldOk.setText(doubleAux.toString());                    
            }
            else{
                totalField.setText("");
            }
        }
        return true;        
        
    }


    private void updateMaterial() {
        
        materialButton.setEnabled(true);    
        if (Utils.isLoaded()) {
            if (materialComboBox.getSelectedItem() instanceof Material) {
                materialButton.setEnabled(true);
                material = (Material) materialComboBox.getSelectedItem();
                Double price = GenericController.getMaterialPvp(material.getId());
                String sPrice = price.toString();
                priceFieldOk.setText(sPrice);
                updateTotal();                
            } else {
                materialButton.setEnabled(false);     
                material = null;
            }
        } 
        
    }

    
    private void prepareReport(){
        
        String where = null;
        if (dateStart != null) {
            where = "WHERE ";
            where += "date_rel >= '" + Utils.dateToString(dateStart) + "'";
        }
        if (dateEnd != null) {
            where = (where == null) ? "WHERE " : where + " AND ";
            where += "date_rel <= '" + Utils.dateToString(dateEnd) + "'";
        }
        if (building != null) {
            where = (where == null) ? "WHERE " : where + " AND ";
            where += "building_id = '" + building.getId() + "'";
        }        
        ExcelManager.reportMaterialsBuilding(where, Utils.dateToString(dateStart), Utils.dateToString(dateEnd));
        
    }
    
    
    private void openMaterialFrame(){
        JFrame frame = new JFrame();
        frame.setContentPane(new MaterialPanel(material, this));
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    
    
    @Override
    protected void newRecord() {
        
        mb = new MaterialBuilding();
        entityManager.persist(mb);
        tableList.add(mb);
        materialComboBox.setSelectedIndex(-1);
        priceFieldOk.setText("");
        amountFieldOk.setText("");
        totalField.setText("");
        super.newRecord();
        if (savedBuilding != null){
            buildingComboBox.setSelectedItem(savedBuilding);
        }
        if (savedDateRel != null){
            dateRelDateChooser.setDate(savedDateRel);
        }    
        materialButton.setEnabled(true);    
        logger.info("MaterialBuilding.new");
        
    }


    @Override
    protected void refresh(Query queryParam, List<?> listObject) {
        refreshWorker = new RefreshWorker(this, entityManager, queryParam, listObject);
        refreshWorker.execute();
        savedBuilding = null;
        savedDateRel = null;
        mb = null;
    }


    @Override
    protected void save() throws RuntimeException{

        savedDateRel = dateRelDateChooser.getDate();
        if (savedDateRel == null){
            JOptionPane.showMessageDialog(this, "Cal especificar la data", bundle.getString("VALIDATE_FORM"), JOptionPane.WARNING_MESSAGE);
            dateRelDateChooser.requestFocusInWindow();
            return;            
        }

        // Get Building
        savedBuilding = (Building) buildingComboBox.getSelectedItem();
        if (savedBuilding == null) {
            JOptionPane.showMessageDialog(this, "Cal especificar edifici o esdeveniment", bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            buildingComboBox.requestFocusInWindow();
            return;
        }    
        
        // Get Material
        Material materialSelected = (Material) materialComboBox.getSelectedItem();
        if (materialSelected == null) {
            JOptionPane.showMessageDialog(this, "Cal especificar material", bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            materialComboBox.requestFocusInWindow();
            return;
        }    
        
        int selected = masterTable.getSelectedRow();
        if (selected > -1) {
            MaterialBuilding object = tableList.get(masterTable.convertRowIndexToModel(selected));
            MaterialBuildingJpaController dao = new MaterialBuildingJpaController();
            try {
                if (object.getId() == null) {
                    if (object.getBuildingId() != null){
                        logger.info("Building: " + object.getBuildingId().getDescription());
                    }
                    if (object.getMaterialId() != null){                    
                        logger.info("Material: " + object.getMaterialId().getDescription());
                    }
                    dao.create(object);
                    logger.info("MaterialBuilding.create: " + object.getId());
                } else {
                    dao.edit(object);
                    logger.info("MaterialBuilding.edit: " + object.getId());
                }
                mb = null;
            } catch (NonexistentEntityException ex) {
                logger.severe(ex.getMessage());
            } catch (Exception ex) {
                logger.severe(ex.getMessage());
            }
        }
        
    }


    @Override
    protected void delete() {
        
        if (deleteConfirm()) {
            List<MaterialBuilding> toRemove = new ArrayList<>(masterTable.getSelectedRows().length);
            MaterialBuildingJpaController dao = new MaterialBuildingJpaController();
            for (int idx = 0; idx < masterTable.getSelectedRows().length; idx++) {
                MaterialBuilding object = tableList.get(masterTable.convertRowIndexToModel(masterTable.getSelectedRows()[idx]));
                try {
                    toRemove.add(object);
                    dao.destroy(object.getId());
                    logger.info("MaterialBuilding.delete: " + object.getId());
                } catch (NonexistentEntityException ex) {
                    logger.severe(ex.getMessage());
                }
            }
            tableList.removeAll(toRemove);
        }
        
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings({ "unchecked" })
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        tableQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryMaterialBuilding"));
        tableList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(tableQuery.getResultList());
        buildingQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryBuilding"));
        buildingList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : buildingQuery.getResultList();
        materialQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryMaterial"));
        materialList = Beans.isDesignTime() ? java.util.Collections.emptyList() : materialQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        idLabel = new javax.swing.JLabel();
        buildingIdLabel = new javax.swing.JLabel();
        materialIdLabel = new javax.swing.JLabel();
        dateRelLabel = new javax.swing.JLabel();
        priceLabel = new javax.swing.JLabel();
        amountLabel = new javax.swing.JLabel();
        totalLabel = new javax.swing.JLabel();
        commentsLabel = new javax.swing.JLabel();
        totalField = new javax.swing.JTextField();
        buildingComboBox = new javax.swing.JComboBox();
        materialComboBox = new javax.swing.JComboBox();
        dateRelDateChooser = new com.toedter.calendar.JDateChooser();
        buttonsPanel = new javax.swing.JPanel();
        nextButton = new javax.swing.JButton();
        previousButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        dateStartDateChooser = new com.toedter.calendar.JDateChooser();
        staffIdLabel1 = new javax.swing.JLabel();
        filterMaterialComboBox = new javax.swing.JComboBox();
        staffIdLabel2 = new javax.swing.JLabel();
        resetButton = new javax.swing.JButton();
        staffIdLabel3 = new javax.swing.JLabel();
        dateEndDateChooser = new com.toedter.calendar.JDateChooser();
        staffIdLabel4 = new javax.swing.JLabel();
        filterBuildingComboBox = new javax.swing.JComboBox();
        priceField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        reportButton = new javax.swing.JButton();
        materialButton = new javax.swing.JButton();
        priceFieldOk = new javax.swing.JTextField();
        amountFieldOk = new javax.swing.JTextField();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tableList, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${buildingId}"));
        columnBinding.setColumnName("Edifici");
        columnBinding.setColumnClass(org.gesplan.entity.Building.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${materialId}"));
        columnBinding.setColumnName("Material");
        columnBinding.setColumnClass(org.gesplan.entity.Material.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${dateRel}"));
        columnBinding.setColumnName("Data");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}"));
        columnBinding.setColumnName("Preu");
        columnBinding.setColumnClass(Float.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${amount}"));
        columnBinding.setColumnName("Quantitat");
        columnBinding.setColumnClass(Float.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${total}"));
        columnBinding.setColumnName("Total");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);
        this.jTableBinding = jTableBinding;

        idLabel.setText("Id:");

        buildingIdLabel.setText("Edifici:");

        materialIdLabel.setText("Material:");

        dateRelLabel.setText("Date Rel:");

        priceLabel.setText("Preu:");

        amountLabel.setText("Quantitat:");

        totalLabel.setText("Total:");

        commentsLabel.setText("Comentaris:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.total}"), totalField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("false"), totalField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, buildingList, buildingComboBox, "buildingBind");
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.buildingId}"), buildingComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "buildingBindSelected");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), buildingComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, materialList, materialComboBox, "materialBind");
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.materialId}"), materialComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"), "materialBindSelected");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), materialComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        materialComboBox.addActionListener(formListener);

        dateRelDateChooser.setToolTipText("dd-MM-yyyy");
        dateRelDateChooser.setDateFormatString("dd-MM-yyyy");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.dateRel}"), dateRelDateChooser, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), dateRelDateChooser, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        nextButton.setMnemonic('S');
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/gesplan/properties/Bundle"); // NOI18N
        nextButton.setText(bundle.getString("NEXT")); // NOI18N
        nextButton.addActionListener(formListener);

        previousButton.setMnemonic('A');
        previousButton.setText(bundle.getString("PREVIOUS")); // NOI18N
        previousButton.addActionListener(formListener);

        refreshButton.setMnemonic('T');
        refreshButton.setText(bundle.getString("REFRESH")); // NOI18N
        refreshButton.addActionListener(formListener);

        saveButton.setMnemonic('G');
        saveButton.setText(bundle.getString("SAVE")); // NOI18N
        saveButton.addActionListener(formListener);

        deleteButton.setMnemonic('E');
        deleteButton.setText(bundle.getString("DELETE")); // NOI18N
        deleteButton.addActionListener(formListener);

        newButton.setMnemonic('N');
        newButton.setText(bundle.getString("NEW")); // NOI18N
        newButton.addActionListener(formListener);

        javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel);
        buttonsPanel.setLayout(buttonsPanelLayout);
        buttonsPanelLayout.setHorizontalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(previousButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nextButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(refreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(32, Short.MAX_VALUE))
        );
        buttonsPanelLayout.setVerticalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(refreshButton)
                    .addComponent(deleteButton)
                    .addComponent(newButton)
                    .addComponent(previousButton)
                    .addComponent(nextButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        dateStartDateChooser.setToolTipText("dd-mm-yyyy"); // NOI18N
        dateStartDateChooser.setDateFormatString("dd-MM-yyyy");
        dateStartDateChooser.addPropertyChangeListener(formListener);

        staffIdLabel1.setText("Edifici:");

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, materialList, filterMaterialComboBox, "");
        bindingGroup.addBinding(jComboBoxBinding);

        filterMaterialComboBox.addActionListener(formListener);

        staffIdLabel2.setText("Data:");

        resetButton.setMnemonic('R');
        resetButton.setText(bundle.getString("RESET")); // NOI18N
        resetButton.addActionListener(formListener);

        staffIdLabel3.setText("Fins:");

        dateEndDateChooser.setDateFormatString("dd-MM-yyyy");
        dateEndDateChooser.addPropertyChangeListener(formListener);

        staffIdLabel4.setText("Material:");

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, buildingList, filterBuildingComboBox, "filterBuildingBind");
        bindingGroup.addBinding(jComboBoxBinding);

        filterBuildingComboBox.addActionListener(formListener);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.id}"), priceField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("false"), priceField1, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(2);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.comments}"), jTextArea1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), jTextArea1, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setViewportView(jTextArea1);

        reportButton.setMnemonic('R');
        reportButton.setText("Informe");
        reportButton.addActionListener(formListener);

        materialButton.setMnemonic('R');
        materialButton.setText(bundle.getString("MATERIAL")); // NOI18N
        materialButton.addActionListener(formListener);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.price}"), priceFieldOk, org.jdesktop.beansbinding.BeanProperty.create("text"), "price");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), priceFieldOk, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        priceFieldOk.addFocusListener(formListener);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.amount}"), amountFieldOk, org.jdesktop.beansbinding.BeanProperty.create("text"), "amount");
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), amountFieldOk, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        amountFieldOk.addFocusListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 612, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(idLabel)
                                    .addComponent(materialIdLabel)
                                    .addComponent(priceLabel))
                                .addGap(16, 16, 16))
                            .addComponent(commentsLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jScrollPane1)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(priceFieldOk, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(31, 31, 31)
                                                .addComponent(amountLabel)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(amountFieldOk, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(totalLabel)
                                                .addGap(18, 18, 18)
                                                .addComponent(totalField, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(5, 5, 5)
                                        .addComponent(materialComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addGap(18, 18, 18)
                                .addComponent(materialButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(12, 12, 12))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(buildingComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(priceField1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(34, 34, 34)
                                        .addComponent(dateRelLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(dateRelDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 253, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buildingIdLabel)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(staffIdLabel2)
                                    .addComponent(staffIdLabel1)
                                    .addComponent(staffIdLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(filterBuildingComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(dateStartDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(staffIdLabel3)
                                        .addGap(18, 18, 18)
                                        .addComponent(dateEndDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(filterMaterialComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(22, 22, 22)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(resetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(reportButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(dateStartDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dateEndDateChooser, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(staffIdLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(staffIdLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filterBuildingComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(staffIdLabel1)
                    .addComponent(reportButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(staffIdLabel4)
                    .addComponent(filterMaterialComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(resetButton))
                .addGap(18, 18, 18)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(idLabel)
                        .addComponent(dateRelLabel)
                        .addComponent(priceField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dateRelDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buildingIdLabel)
                    .addComponent(buildingComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(materialIdLabel)
                    .addComponent(materialComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(materialButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(amountLabel)
                    .addComponent(priceLabel)
                    .addComponent(totalLabel)
                    .addComponent(totalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(priceFieldOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(amountFieldOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(commentsLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 14, Short.MAX_VALUE)
                .addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.FocusListener, java.beans.PropertyChangeListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == materialComboBox) {
                MaterialBuildingPanel.this.materialComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == nextButton) {
                MaterialBuildingPanel.this.nextButtonActionPerformed(evt);
            }
            else if (evt.getSource() == previousButton) {
                MaterialBuildingPanel.this.previousButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                MaterialBuildingPanel.this.refreshButtonActionPerformed(evt);
            }
            else if (evt.getSource() == saveButton) {
                MaterialBuildingPanel.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == deleteButton) {
                MaterialBuildingPanel.this.deleteButtonActionPerformed(evt);
            }
            else if (evt.getSource() == newButton) {
                MaterialBuildingPanel.this.newButtonActionPerformed(evt);
            }
            else if (evt.getSource() == filterMaterialComboBox) {
                MaterialBuildingPanel.this.filterMaterialComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == resetButton) {
                MaterialBuildingPanel.this.resetButtonActionPerformed(evt);
            }
            else if (evt.getSource() == filterBuildingComboBox) {
                MaterialBuildingPanel.this.filterBuildingComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == reportButton) {
                MaterialBuildingPanel.this.reportButtonActionPerformed(evt);
            }
            else if (evt.getSource() == materialButton) {
                MaterialBuildingPanel.this.materialButtonActionPerformed(evt);
            }
        }

        public void focusGained(java.awt.event.FocusEvent evt) {
            if (evt.getSource() == priceFieldOk) {
                MaterialBuildingPanel.this.priceFieldOkFocusGained(evt);
            }
            else if (evt.getSource() == amountFieldOk) {
                MaterialBuildingPanel.this.amountFieldOkFocusGained(evt);
            }
        }

        public void focusLost(java.awt.event.FocusEvent evt) {
            if (evt.getSource() == priceFieldOk) {
                MaterialBuildingPanel.this.priceFieldOkFocusLost(evt);
            }
            else if (evt.getSource() == amountFieldOk) {
                MaterialBuildingPanel.this.amountFieldOkFocusLost(evt);
            }
        }

        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            if (evt.getSource() == dateStartDateChooser) {
                MaterialBuildingPanel.this.dateStartDateChooserPropertyChange(evt);
            }
            else if (evt.getSource() == dateEndDateChooser) {
                MaterialBuildingPanel.this.dateEndDateChooserPropertyChange(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents


    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        next();
        updateTotal();        
    }//GEN-LAST:event_nextButtonActionPerformed

    private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
        previous();
        updateTotal();        
    }//GEN-LAST:event_previousButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        refresh(tableQuery);
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (updateTotal()){
            try {
                save();
            } catch (RuntimeException e) {
                logger.warning(e.getMessage());
                JOptionPane.showMessageDialog(this, bundle.getString("ERROR_DB_SAVE") + "\n" + bundle.getString("SEE_LOG"),
                    bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            }        
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        delete();
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        newRecord();
    }//GEN-LAST:event_newButtonActionPerformed

    private void dateStartDateChooserPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateStartDateChooserPropertyChange
        changeFilter();
    }//GEN-LAST:event_dateStartDateChooserPropertyChange

    private void filterMaterialComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterMaterialComboBoxActionPerformed
        changeFilter();
    }//GEN-LAST:event_filterMaterialComboBoxActionPerformed

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        resetFilters();
    }//GEN-LAST:event_resetButtonActionPerformed

    private void dateEndDateChooserPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateEndDateChooserPropertyChange
        changeFilter();
    }//GEN-LAST:event_dateEndDateChooserPropertyChange

    private void filterBuildingComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterBuildingComboBoxActionPerformed
        changeFilter();
    }//GEN-LAST:event_filterBuildingComboBoxActionPerformed

    private void materialComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_materialComboBoxActionPerformed
        updateMaterial();
    }//GEN-LAST:event_materialComboBoxActionPerformed

    private void reportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reportButtonActionPerformed
        prepareReport();
    }//GEN-LAST:event_reportButtonActionPerformed

    private void materialButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_materialButtonActionPerformed
        openMaterialFrame();
    }//GEN-LAST:event_materialButtonActionPerformed

    private void priceFieldOkFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_priceFieldOkFocusLost
        updateTotal();
    }//GEN-LAST:event_priceFieldOkFocusLost

    private void amountFieldOkFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_amountFieldOkFocusLost
        updateTotal();
    }//GEN-LAST:event_amountFieldOkFocusLost

    private void priceFieldOkFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_priceFieldOkFocusGained
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                priceFieldOk.selectAll();
            }
        });
    }//GEN-LAST:event_priceFieldOkFocusGained

    private void amountFieldOkFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_amountFieldOkFocusGained
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                amountFieldOk.selectAll();
            }
        });
    }//GEN-LAST:event_amountFieldOkFocusGained

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField amountFieldOk;
    private javax.swing.JLabel amountLabel;
	private javax.swing.JComboBox buildingComboBox;
    private javax.swing.JLabel buildingIdLabel;
    private java.util.List buildingList;
    private javax.persistence.Query buildingQuery;
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JLabel commentsLabel;
    private com.toedter.calendar.JDateChooser dateEndDateChooser;
    private com.toedter.calendar.JDateChooser dateRelDateChooser;
    private javax.swing.JLabel dateRelLabel;
    private com.toedter.calendar.JDateChooser dateStartDateChooser;
    private javax.swing.JButton deleteButton;
    private javax.swing.JComboBox filterBuildingComboBox;
    private javax.swing.JComboBox filterMaterialComboBox;
    private javax.swing.JLabel idLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton materialButton;
    private javax.swing.JComboBox materialComboBox;
    private javax.swing.JLabel materialIdLabel;
    private java.util.List<org.gesplan.entity.Material> materialList;
    private javax.persistence.Query materialQuery;
    private javax.swing.JButton newButton;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton previousButton;
    private javax.swing.JTextField priceField1;
    private javax.swing.JTextField priceFieldOk;
    private javax.swing.JLabel priceLabel;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton reportButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel staffIdLabel1;
    private javax.swing.JLabel staffIdLabel2;
    private javax.swing.JLabel staffIdLabel3;
    private javax.swing.JLabel staffIdLabel4;
    private java.util.List<org.gesplan.entity.MaterialBuilding> tableList;
    private javax.persistence.Query tableQuery;
    private javax.swing.JTextField totalField;
    private javax.swing.JLabel totalLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables


    public static void main(String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MaterialBuildingPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MaterialBuildingPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MaterialBuildingPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MaterialBuildingPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new MaterialBuildingPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    
}